﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace NGenORM.Library.Util
{
    public class ConnectionFactorySQLServer : ConnectionFactory
    {

        /// <summary>
        /// Instancia um objeto de Conexão
        /// </summary>
        /// <param name="Conexao">Objeto de Conexão</param>
        /// <remarks></remarks>
        public override SqlConnection CreateConnection()
        {

            connection = new SqlConnection();

            try {

                if (IntegratedSecurity == true) {
                    connection.ConnectionString = "data source = " + Datasource + "; trusted_connection=true; database = " + Database + ";";
                }
                else {
                    connection.ConnectionString = "data source = " + Datasource + "; trusted_connection=false; database = " + Database + "; User ID = " + UserID + "; Password = " + Password + ";";
                }

                return connection;
            }
            catch (Exception) {
                throw new Exception("Criar Conexão:: Tempo Esgotado");
            }

        }

        /// <summary>
        /// Abre a Conexão
        /// </summary>
        /// <param name="Conexao">Objeto de Conexão do tipo SqlConnection</param>
        /// <remarks></remarks>
        public override bool OpenConnection() {

            try {
                //CreateConnection();

                if (connection.State == ConnectionState.Open) {
                    throw new Exception("Open Connection: Connection is already open");
                }
                else {
                    connection.Open();
                    return true;
                }
            }
            catch (Exception ex) {
                throw ex;
            }

        }

        public override bool CloseConnection()
        {

            if (connection.State == System.Data.ConnectionState.Open)
            {
                connection.Close();
                connection.Dispose();
                return true;
                //Else
                //Throw New Exception("Nenhuma conexão aberta foi encontrada")
            }
            else { return false; }
            //End If
        }

        public override bool TestConnection() {
            CreateConnection();
            return OpenConnection();
        }


    }
}
